package com.wxq.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class NetClient {

	/*
	 *  List<NameValuePair> params = new ArrayList<NameValuePair>();   
        params.add(new BasicNameValuePair("name", "wxq"));   
        params.add(new BasicNameValuePair("password", "954619"));
	 */
	
	public static String doPost(String url,List <NameValuePair> params)
	{
		String result = null;
		HttpPost httpRequest = new HttpPost(url);   
		try 
		{
			 //发出HTTP request   
			/*
			 * 服务器端设置
			 *  1.将JSP页面的头部改为如上的第一行。
				2.在代码的第一行添加request.setCharacterEncoding("UTF-8");  
				3.接收参数的时候使用语法： request.getParameter("name");

			 * */
			
		     httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));   
		     //取得HTTP response   
		     HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
		     
		     //若状态码为200 ok 
		     if(httpResponse.getStatusLine().getStatusCode()==200)
		     {   
			      //取出回应字串   
		    	  result = EntityUtils.toString(httpResponse.getEntity());   
			       
		     }
		     else
		     {   
		          result = null;
		     }   		     
		} 
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}		
		return result;
	}
	
	public static String doGet(String url) {
		StringBuilder response = new StringBuilder();
		URL u = null;
		try {
			u = new URL(url);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpURLConnection httpConn = null;
		try {
			httpConn = (HttpURLConnection) u.openConnection();
			if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
			{
				BufferedReader input = new BufferedReader(
						new InputStreamReader(httpConn.getInputStream()), 
						8192);
				String strLine = null;
				while((strLine = input.readLine())!=null)
				{
					response.append(strLine);
				}
				input.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return response.toString();
	}
}
